import shutil
import uuid
import os
from datetime import datetime

from fastapi import APIRouter, UploadFile
from fastapi_amis_admin.globals.deps import AsyncSess, SyncSess
from starlette.responses import FileResponse

from ..common import ApiResult, CommonUtil
from .models import SysBasicFile
from backend.core.settings import settings

router = APIRouter()

@router.post('/upload')
async def upload(file: UploadFile, sess: SyncSess):
    """
    文件上传
    :param file:
    :param sess:
    :return:
    """
    try:
        uid = str(uuid.uuid4())
        suffix = CommonUtil.get_file_extension(file.filename)
        date_dir = datetime.now().strftime("%Y%m%d")
        upload_path = f"/upload/{date_dir}"
        relative_path = f"{upload_path}/{uid}{suffix}"
        CommonUtil.create_directory(f"{settings.file_store_path}/{upload_path}")
        with open(f"{settings.file_store_path}{relative_path}", "wb") as buffer:
            shutil.copyfileobj(file.file, buffer)
    finally:
        file.file.close()

    fileModel = SysBasicFile(file_id=uid, name=file.filename, origin_name=file.filename, size=file.size, relative_path=relative_path, )
    sess.add(fileModel)
    return ApiResult(data=fileModel)


@router.get("/download/{fileId}")
async def download_file(fileId: str, sess: SyncSess):
    """
    文件下载
    :param fileId:
    :param sess:
    :return:
    """
    basicFile = sess.query(SysBasicFile).filter(SysBasicFile.file_id == fileId).first()
    if not basicFile:
        return ApiResult(code=400, msg="文件不存在！")
    file_path = f"{settings.file_store_path}{basicFile.relative_path}"
    print(file_path)
    return FileResponse(file_path, media_type="application/octet-stream", filename=basicFile.origin_name)
